package io.sundial.discovery.impl;

import io.sundial.core.context.Context;
import io.sundial.core.lifecycle.exception.InitializingException;
import io.sundial.job.Job;
import io.sundial.util.IteratorEnumeration;

import java.util.Enumeration;
import java.util.Objects;
import java.util.ServiceLoader;

/**
 * 服务加载方式的作业发现者
 *
 * @author Payne 646742615@qq.com
 * 2018/12/26 19:31
 */
public class ServiceLoadingDiscoverer extends ClassLoadingDiscoverer {

    public ServiceLoadingDiscoverer() {
    }

    public ServiceLoadingDiscoverer(ClassLoader classLoader) {
        super(classLoader);
    }

    @Override
    protected void initializing(Context context) throws InitializingException {
        super.initializing(context);

        Enumeration<Job> enumeration = jobs();
        while (enumeration.hasMoreElements()) {
            Job job = enumeration.nextElement();
            save(job);
        }
    }

    @Override
    protected Job find(String jobName, String jobGroup) {
        Enumeration<Job> enumeration = jobs();
        while (enumeration.hasMoreElements()) {
            Job job = enumeration.nextElement();
            if (Objects.equals(jobName, job.name()) && Objects.equals(jobGroup, job.group())) {
                return job;
            }
        }
        return null;
    }

    @Override
    public Enumeration<Job> jobs() {
        ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            ClassLoader newClassLoader = getClassLoader();
            Thread.currentThread().setContextClassLoader(newClassLoader);
            ServiceLoader<Job> serviceLoader = ServiceLoader.load(Job.class, newClassLoader);
            return new IteratorEnumeration<>(serviceLoader.iterator());
        } finally {
            Thread.currentThread().setContextClassLoader(oldClassLoader);
        }
    }

}
